<template>
  <view class="logs-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
        </view>
        <view class="page-title">操作日志</view>
      </view>
      <!-- 波浪背景装饰 -->
      <view class="wave-box">
        <view class="wave wave-1"></view>
        <view class="wave wave-2"></view>
      </view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-area">
      <view class="filter-row">
        <u-dropdown :close-on-click-mask="true" :close-on-click-self="true">
          <u-dropdown-item v-model="moduleFilter" title="操作模块" :options="moduleOptions"></u-dropdown-item>
          <u-dropdown-item v-model="actionFilter" title="操作类型" :options="actionOptions"></u-dropdown-item>
          <u-dropdown-item v-model="dateFilter" title="时间范围" :options="dateOptions"></u-dropdown-item>
        </u-dropdown>
      </view>

      <view class="filter-row search-row">
        <u-search
          v-model="searchKeyword"
          placeholder="搜索操作内容或对象名称"
          :show-action="true"
          action-text="搜索"
          @search="handleSearch"
          @custom="handleSearch"
        ></u-search>
      </view>
    </view>

    <!-- 日志列表 -->
    <view class="log-list">
      <u-empty v-if="logData.length === 0" mode="list" text="暂无操作日志"></u-empty>

      <view v-else>
        <view class="list-header">
          <text>共找到 {{total}} 条记录</text>
          <view class="export-btn" @click="exportLogs">
            <u-icon name="archive" size="16" color="#007aff"></u-icon>
            <text>导出</text>
          </view>
        </view>

        <view
          class="log-item animate-item"
          v-for="(item, index) in logData"
          :key="index"
          :style="{ animationDelay: index * 0.05 + 's' }"
          @click="showLogDetail(item)"
        >
          <view class="log-header">
            <view class="log-title">
              <text>{{item.action}}</text>
              <text class="log-type">{{item.target_type}}</text>
              <text v-if="item.target_name">: {{item.target_name}}</text>
            </view>
            <view :class="['log-module', getModuleClass(item.module)]">{{item.module}}</view>
          </view>

          <view class="log-content">
            <text>{{formatContent(item.content)}}</text>
          </view>

          <view class="log-footer">
            <view class="log-user">
              <u-icon name="account" size="14" color="#666"></u-icon>
              <text>{{item.manager_name || '未知用户'}}</text>
            </view>
            <view class="log-time">
              <u-icon name="calendar" size="14" color="#666"></u-icon>
              <text>{{formatDate(item.created_at)}}</text>
            </view>
            <view class="log-device" v-if="item.device_info">
              <u-icon name="smartphone" size="14" color="#666"></u-icon>
              <text>{{formatDevice(item.device_info)}}</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <u-loadmore
          :status="loadStatus"
          @loadmore="loadMore"
          :icon-type="iconType"
          margin-top="15"
          margin-bottom="15"
        />
      </view>
    </view>

    <!-- 日志详情弹窗 -->
    <u-popup v-model="showDetailPopup" mode="center" width="80%" border-radius="16">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="popup-title">操作详情</text>
          <u-icon name="close" size="24" color="#999" @click="showDetailPopup = false"></u-icon>
        </view>

        <scroll-view scroll-y class="popup-content">
          <view class="detail-item">
            <view class="detail-label">操作模块</view>
            <view class="detail-value">{{currentLog.module}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">操作类型</view>
            <view class="detail-value">{{currentLog.action}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">操作对象</view>
            <view class="detail-value">{{currentLog.target_type}} {{currentLog.target_name || ''}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">对象ID</view>
            <view class="detail-value">{{currentLog.target_id || '-'}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">操作人</view>
            <view class="detail-value">{{currentLog.manager_name || '未知用户'}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">操作时间</view>
            <view class="detail-value">{{formatDate(currentLog.created_at, true)}}</view>
          </view>
          <view class="detail-item">
            <view class="detail-label">设备信息</view>
            <view class="detail-value">{{currentLog.device_info || '-'}}</view>
          </view>
          <view class="detail-item content-item">
            <view class="detail-label">操作内容</view>
            <view class="detail-value content-value">{{formatDetailContent(currentLog.content)}}</view>
          </view>
        </scroll-view>

        <view class="popup-footer">
          <u-button type="primary" @click="showDetailPopup = false">关闭</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import request from "@/utils/request.js";
import { formatTime } from "@/utils/util.js";
import { LOG_MODULE, LOG_ACTION, TARGET_TYPE } from "@/utils/logger.js";

export default {
  data() {
    return {
      // 筛选条件
      moduleFilter: "",
      actionFilter: "",
      dateFilter: "",
      searchKeyword: "",

      // 筛选选项
      moduleOptions: this.getModuleOptions(),
      actionOptions: this.getActionOptions(),
      dateOptions: [
        { label: "全部时间", value: "" },
        { label: "今天", value: "today" },
        { label: "最近7天", value: "week" },
        { label: "最近30天", value: "month" }
      ],

      // 日志数据
      logData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      loadStatus: "loadmore",
      iconType: "flower",

      // 日志详情
      showDetailPopup: false,
      currentLog: {}
    };
  },
  onLoad() {
    this.fetchLogs();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 获取模块选项
    getModuleOptions() {
      const options = [{ label: "全部模块", value: "" }];

      for (const key in LOG_MODULE) {
        options.push({
          label: LOG_MODULE[key],
          value: LOG_MODULE[key]
        });
      }

      return options;
    },

    // 获取操作类型选项
    getActionOptions() {
      const options = [{ label: "全部操作", value: "" }];

      for (const key in LOG_ACTION) {
        options.push({
          label: LOG_ACTION[key],
          value: LOG_ACTION[key]
        });
      }

      return options;
    },

    // 搜索操作
    handleSearch() {
      this.page = 1;
      this.logData = [];
      this.fetchLogs();
    },

    // 获取日志数据
    async fetchLogs() {
      try {
        this.loadStatus = "loading";

        // 构建查询参数
        const params = {
          page: this.page,
          limit: this.pageSize,
          module: this.moduleFilter,
          action: this.actionFilter
        };

        // 添加关键词搜索
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }

        // 添加日期筛选
        if (this.dateFilter) {
          const now = new Date();
          let startDate = new Date();

          switch (this.dateFilter) {
            case "today":
              startDate.setHours(0, 0, 0, 0);
              break;
            case "week":
              startDate.setDate(startDate.getDate() - 7);
              break;
            case "month":
              startDate.setDate(startDate.getDate() - 30);
              break;
          }

          params.start_date = startDate.toISOString().split("T")[0];
          params.end_date = now.toISOString().split("T")[0];
        }

        // 发送请求
        const res = await request.sendRequest("operation-logs", "GET", params);

        if (res.data && res.data.code === 200) {
          const { data, meta } = res.data.data;

          if (this.page === 1) {
            this.logData = data;
          } else {
            this.logData = [...this.logData, ...data];
          }

          this.total = meta.total;

          // 更新加载状态
          if (this.logData.length >= meta.total) {
            this.loadStatus = "nomore";
          } else {
            this.loadStatus = "loadmore";
          }
        } else {
          this.loadStatus = "loadmore";
          uni.showToast({
            title: "获取日志失败",
            icon: "none"
          });
        }
      } catch (error) {
        console.error("获取日志异常", error);
        this.loadStatus = "loadmore";
        uni.showToast({
          title: "获取日志异常",
          icon: "none"
        });
      }
    },

    // 加载更多
    loadMore() {
      if (this.loadStatus !== "nomore") {
        this.page++;
        this.fetchLogs();
      }
    },

    // 显示日志详情
    showLogDetail(log) {
      this.currentLog = log;
      this.showDetailPopup = true;
    },

    // 格式化日期
    formatDate(dateStr, showTime = false) {
      if (!dateStr) return "-";

      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      if (showTime) {
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      return `${year}-${month}-${day}`;
    },

    // 格式化内容（简短版本）
    formatContent(content) {
      if (!content) return "无操作内容";

      try {
        // 尝试解析JSON
        const jsonContent = JSON.parse(content);

        if (typeof jsonContent === "object") {
          // 如果是对象，提取简短描述
          if (jsonContent.description) {
            return jsonContent.description;
          } else {
            // 创建简短摘要
            const keys = Object.keys(jsonContent).slice(0, 3);
            return (
              keys.map(key => `${key}: ${jsonContent[key]}`).join(", ") +
              (Object.keys(jsonContent).length > 3 ? "..." : "")
            );
          }
        }

        return content;
      } catch (e) {
        // 不是JSON，直接返回
        return content.length > 100
          ? content.substring(0, 100) + "..."
          : content;
      }
    },

    // 格式化详细内容
    formatDetailContent(content) {
      if (!content) return "无操作内容";

      try {
        // 尝试解析JSON并美化显示
        const jsonContent = JSON.parse(content);
        return JSON.stringify(jsonContent, null, 2);
      } catch (e) {
        // 不是JSON，直接返回
        return content;
      }
    },

    // 格式化设备信息
    formatDevice(deviceInfo) {
      if (!deviceInfo) return "-";

      // 简化设备信息显示
      const parts = deviceInfo.split(" ");
      if (parts.length > 2) {
        return `${parts[0]} ${parts[1]}`;
      }
      return deviceInfo;
    },

    // 获取模块样式类
    getModuleClass(module) {
      const moduleMap = {
        [LOG_MODULE.GROUP]: "module-group",
        [LOG_MODULE.BUSINESS_BASIC]: "module-basic",
        [LOG_MODULE.BUSINESS_FOLLOW]: "module-follow",
        [LOG_MODULE.BUSINESS_EXPANSION]: "module-expansion",
        [LOG_MODULE.STATISTICS]: "module-stats",
        [LOG_MODULE.TODO]: "module-todo",
        [LOG_MODULE.SYSTEM]: "module-system"
      };

      return moduleMap[module] || "module-default";
    },

    // 导出日志
    exportLogs() {
      uni.showModal({
        title: "导出确认",
        content: "确认导出当前筛选条件下的所有日志数据？",
        success: async res => {
          if (res.confirm) {
            uni.showLoading({
              title: "正在导出"
            });

            try {
              // 构建导出参数，与查询参数相同
              const params = {
                module: this.moduleFilter,
                action: this.actionFilter,
                export: true
              };

              if (this.searchKeyword) {
                params.keyword = this.searchKeyword;
              }

              if (this.dateFilter) {
                const now = new Date();
                let startDate = new Date();

                switch (this.dateFilter) {
                  case "today":
                    startDate.setHours(0, 0, 0, 0);
                    break;
                  case "week":
                    startDate.setDate(startDate.getDate() - 7);
                    break;
                  case "month":
                    startDate.setDate(startDate.getDate() - 30);
                    break;
                }

                params.start_date = startDate.toISOString().split("T")[0];
                params.end_date = now.toISOString().split("T")[0];
              }

              // 发送导出请求
              const res = await request.sendRequest(
                "operation-logs/export",
                "GET",
                params
              );

              uni.hideLoading();

              if (res.data && res.data.code === 200) {
                const fileUrl = res.data.data.fileUrl;

                // 打开文件或提供下载链接
                // H5环境
                if (process.env.VUE_APP_PLATFORM === "h5") {
                  window.open(fileUrl);
                } else {
                  // 原生环境
                  uni.downloadFile({
                    url: fileUrl,
                    success: res => {
                      if (res.statusCode === 200) {
                        uni.openDocument({
                          filePath: res.tempFilePath,
                          success: () => {
                            console.log("打开文档成功");
                          },
                          fail: () => {
                            uni.showToast({
                              title: "无法打开文件",
                              icon: "none"
                            });
                          }
                        });
                      }
                    },
                    fail: () => {
                      uni.showToast({
                        title: "下载文件失败",
                        icon: "none"
                      });
                    }
                  });
                }
              } else {
                uni.showToast({
                  title: "导出失败",
                  icon: "none"
                });
              }
            } catch (error) {
              uni.hideLoading();
              console.error("导出异常", error);
              uni.showToast({
                title: "导出异常",
                icon: "none"
              });
            }
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.logs-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  position: relative;
  height: 200rpx;
  background: linear-gradient(135deg, #2563eb, #3b82f6);
  color: #fff;
  overflow: hidden;

  .header-content {
    position: relative;
    z-index: 10;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 30rpx;

    .back-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }

    .page-title {
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .wave-box {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 50rpx;

    .wave {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      background: url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 1440 320%22%3E%3Cpath fill=%22%23ffffff%22 fill-opacity=%221%22 d=%22M0,160L60,170.7C120,181,240,203,360,192C480,181,600,139,720,122.7C840,107,960,117,1080,138.7C1200,160,1320,192,1380,208L1440,224L1440,320L1380,320C1320,320,1200,320,1080,320C960,320,840,320,720,320C600,320,480,320,360,320C240,320,120,320,60,320L0,320Z%22%3E%3C/path%3E%3C/svg%3E")
        repeat-x;
      background-size: 1440px 100%;
    }

    .wave-1 {
      opacity: 0.7;
      animation: wave-animation 10s linear infinite;
    }

    .wave-2 {
      opacity: 0.5;
      animation: wave-animation 15s linear infinite reverse;
    }
  }
}

@keyframes wave-animation {
  0% {
    background-position-x: 0;
  }
  100% {
    background-position-x: 1440px;
  }
}

.filter-area {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;

  .filter-row {
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .search-row {
    margin-top: 20rpx;
  }
}

.log-list {
  padding: 30rpx;

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    color: #666;
    font-size: 28rpx;

    .export-btn {
      display: flex;
      align-items: center;
      color: #007aff;

      text {
        margin-left: 10rpx;
      }
    }
  }

  .log-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);

    &.animate-item {
      animation: fadeInUp 0.5s ease forwards;
      opacity: 0;
      transform: translateY(20rpx);
    }

    .log-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;

      .log-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        flex: 1;

        .log-type {
          font-weight: normal;
          margin-left: 10rpx;
          color: #666;
        }
      }

      .log-module {
        font-size: 24rpx;
        padding: 2rpx 14rpx;
        border-radius: 20rpx;

        &.module-group {
          background-color: #ecfdf5;
          color: #10b981;
        }

        &.module-basic {
          background-color: #eff6ff;
          color: #3b82f6;
        }

        &.module-follow {
          background-color: #eef2ff;
          color: #6366f1;
        }

        &.module-expansion {
          background-color: #fef2f2;
          color: #ef4444;
        }

        &.module-stats {
          background-color: #f5f3ff;
          color: #8b5cf6;
        }

        &.module-todo {
          background-color: #fff7ed;
          color: #f59e0b;
        }

        &.module-system {
          background-color: #f3f4f6;
          color: #6b7280;
        }

        &.module-default {
          background-color: #f3f4f6;
          color: #6b7280;
        }
      }
    }

    .log-content {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
      line-height: 1.5;
    }

    .log-footer {
      display: flex;
      flex-wrap: wrap;
      font-size: 24rpx;
      color: #999;

      .log-user,
      .log-time,
      .log-device {
        display: flex;
        align-items: center;
        margin-right: 30rpx;
        margin-bottom: 10rpx;

        text {
          margin-left: 6rpx;
        }
      }
    }
  }
}

.detail-popup {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;

  .popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .popup-content {
    padding: 30rpx;
    max-height: 60vh;

    .detail-item {
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      &.content-item {
        .detail-value {
          background-color: #f9fafb;
          padding: 20rpx;
          border-radius: 8rpx;
          white-space: pre-wrap;
          word-break: break-all;
          font-family: monospace;
          font-size: 24rpx;
          max-height: 300rpx;
          overflow-y: auto;
        }
      }

      .detail-label {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 6rpx;
      }

      .detail-value {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .popup-footer {
    padding: 30rpx;
    border-top: 1px solid #eee;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 